/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.common.util.vm;

import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <请简单说明此类用途>
 * @Title com.enfry.util.vm.VmMsgUtil
 * @author longguangxing
 * @date 2017年10月12日
 */
public class VmMsgUtil {
	private Logger logger = LoggerFactory.getLogger(getClass());

	private VelocityEngine	ve;
	
	private volatile static VmMsgUtil singleton; 
	
	private VmMsgUtil (){
		try {
			String vmPath = this.getClass().getResource("/vm").getPath();
			logger.info("模板加载路径:" + vmPath);
			ve = new VelocityEngine();
			Properties properties = new Properties();
			properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, vmPath);
			ve.init(properties);
		}
		catch (Exception e) {
			logger.error("模板加载失败:" + e.getMessage(), e);
		}
	}   
	
	public static VmMsgUtil getSingleton() {
		if (singleton == null) {
			synchronized (VmMsgUtil.class) {
				if (singleton == null) {
					singleton = new VmMsgUtil();
				}
			}
		}
		return singleton;
	}
	
	private void close(Writer w) {
		try {
			if (w != null) {
				w.close();
			}
		}
		catch (Exception e) {
		}
	}
	
	public String createVmFileContent(List<Map<String,Object>> list, String vmName, Map<String,Object> head) throws Exception {

		Map<String,Object> map = new HashMap<String,Object>();
		if (list != null && !list.isEmpty()) {
			map.put("list", list);
		}
		if (head != null && !head.isEmpty()) {
			map.put("head", head);
		}
		if(StringUtils.isEmpty(vmName)){
			throw new IllegalArgumentException("vmName参数为空~" );
		}
		
		return createVelocity(map, vmName);
	}
	
	public String createVelocity(Map<String,Object> map, String vmName) throws Exception {
		logger.debug("vmName:" + vmName);
		StringWriter writer = null;
		Template template = null;
		VelocityContext context = null;
		try {
			template = ve.getTemplate(vmName);
			// 输出流
			writer = new StringWriter();
			// 取得velocity的上下文context
			context = new VelocityContext(map);
			template.merge(context, writer);

			return writer.toString();
		}
		catch (Exception e) {
			logger.error("组装模板信息出错，请检查模板信息是否正确", e);
			throw new Exception("组装模板信息出错，请检查模板信息是否正确");
		}
		finally {
			template = null;
			context = null;
			close(writer);
		}
	}
}
